package net.daum.webtoon.android.io;

import java.lang.reflect.Field;
import java.util.List;

import net.daum.webtoon.android.dto.DTO_Artist;
import net.daum.webtoon.android.dto.DTO_Cartoon;
import net.daum.webtoon.android.dto.DTO_Category;
import net.daum.webtoon.android.dto.DTO_Episode;
import net.daum.webtoon.android.dto.DTO_EpisodeDatas;
import net.daum.webtoon.android.dto.DTO_EpisodePage;
import net.daum.webtoon.android.dto.DTO_EpisodeToon;
import net.daum.webtoon.android.dto.DTO_Genre;
import net.daum.webtoon.android.dto.DTO_Page;
import net.daum.webtoon.android.dto.DTO_PictureImage;
import net.daum.webtoon.android.dto.DTO_Result;
import net.daum.webtoon.android.dto.DTO_WebToon;
import android.content.Context;
import android.provider.ContactsContract.CommonDataKinds.Organization;

public class DBProvider extends Abatis {
	private static final String TAG = DBProvider.class.getSimpleName();

	private static final String DB_NAME = "WEBTOON";
	private static Class[] DTOCLASSES = { DTO_Artist.class, DTO_Cartoon.class, DTO_Category.class, DTO_Episode.class, DTO_EpisodeDatas.class,
			DTO_EpisodePage.class, DTO_EpisodeToon.class, DTO_Genre.class, DTO_Page.class, DTO_PictureImage.class, DTO_Result.class,
			DTO_WebToon.class };

	private static final String BASEINITTABLESTRING0 = "CREATE TABLE IF NOT EXISTS ";
	private static final String BASEINITTABLESTRING1 = "(id_num INTEGER";
	public static DBProvider gDbProvider;

	public static void initInstance(Context aContext) {
		if (gDbProvider == null) {
			gDbProvider = new DBProvider(aContext);
		}
	}

	public static DBProvider getInstance() {
		return gDbProvider;
	}

	private static String getAllDTOTableString() {
		StringBuilder returnString = new StringBuilder();
		for (Class lClass : DTOCLASSES) {

			returnString.append(BASEINITTABLESTRING0);
			returnString.append(lClass.getSimpleName());
			returnString.append(BASEINITTABLESTRING1);
//			PRIMARY KEY AUTOINCREMENT 
			for (Field lField : lClass.getDeclaredFields()) {
				if (!lField.getName().equalsIgnoreCase("TAG")) {
					returnString.append(", ");
					if (lField.getName().equalsIgnoreCase("id")) {
						returnString.append(lField.getName());
						returnString.append(" INTEGER PRIMARY KEY ");
					} else {
						returnString.append(lField.getName());
						returnString.append(" TEXT");
					}
				}
			}

			returnString.append(") ;");
		}
		return returnString.toString();
	}

	private DBProvider(Context context) {
		super(context, DB_NAME, getAllDTOTableString());
	}

	public List<DTO_WebToon> getWebToons() {
		return executeForBeanDinamicSql("", null, Organization.class);
	}

	final String _VALUE = "_VALUE_";
	final String _TABLE = "_TABLE_";
	final String _NAMES = "_NAMES_";
	String BASEINSERT = "INSERT INTO _TABLE_ ( _NAMES_ ) VALUES ( _VALUE_ )";

	public void insertWebToons(DTO_WebToon aWToon) {
		String[] lKeyValue = aWToon.getAllMemeberValues().split("\n");
		int result = executeDirectSql(BASEINSERT.replace(_TABLE, aWToon.getClass().getSimpleName()).replace(_NAMES, lKeyValue[1])
				.replace(_VALUE, lKeyValue[0]));
	}

//
//	public void setBusiness(Channel channel) {
//		List<Map<String, Object>> paramsList = new ArrayList<Map<String, Object>>();
//		List<Business> businesses = channel.getItems();
//		for (Business business : businesses) {
//			Map<String, Object> params = new HashMap<String, Object>();
//			params.put(Business.KEY_TITLE, business.getTitle().replace("'", "&apos;").replace("ㆍ", "&middot;").replaceAll("#", "&sect;"));
//			params.put(Business.KEY_LINK, business.getLink());
//			params.put(Business.KEY_SEQ, business.getSeq());
//			params.put(Business.KEY_AUTHOR, business.getAuthor());
//			params.put(Business.KEY_DESCRIPTION, business.getDescription().replace("'", "&apos;").replace("ㆍ", "&middot;").replaceAll("#", "&sect;"));
//			params.put(Business.KEY_CATEGORY, business.getCategory());
//			params.put(Business.KEY_PUB_DATE, business.getPubDate());
//			params.put(Business.KEY_REQ_DATE, business.getReqstDt());
//			params.put(Business.KEY_AREA, business.getArea());
//			paramsList.add(params);
//		}
//		executeForParamsList("addBusiness", paramsList);
//	}
//
//	public void resetBusiness(Channel channel) {
//		execute("dropBusinessTable");
//		execute("createBusinessTable");
//		setBusiness(channel);
//	}
//
//	public Business getBusiness(int businessId) {
//		Map<String, Object> params = new HashMap<String, Object>();
//		params.put(Business.KEY_ID, businessId);
//		return executeForBean("getBusiness", params, Business.class);
//	}
//
//	/**
//	 * ORM 에서 동적 쿼리를 제공하지 않아 어쩔 수 없이 퀴즈 맞춤 정보는 코드에서..
//	 * 
//	 * @param aptitudes
//	 *            the aptitudes
//	 * @return the business by aptitude
//	 */
//	public List<Business> getBusinessByQuizPersonalize(String aptitudes) {
//		getDbObject();
//		String[] keywords = aptitudes.split(",");
//		StringBuffer execSQL = new StringBuffer();
//		execSQL.append("SELECT * FROM tb_business WHERE ");
//		int cnt = 1;
//		for (String keyword : keywords) {
//			execSQL.append("title LIKE '%" + keyword.trim() + "%' OR description LIKE '%" + keyword.trim() + "%'");
//			if (cnt++ != keywords.length)
//				execSQL.append(" OR ");
//		}
//		execSQL.append(" ORDER BY title ASC;");
//
//		Logger.d(TAG, "QuizPersonalize [" + execSQL.toString() + "]");
//
//		Cursor cursor = dbObj.rawQuery(execSQL.toString(), null);
//		List<Business> businesses = new ArrayList<Business>();
//		while (cursor.moveToNext()) {
//			Business business = new Business();
//			int idx = 0;
//			business.setId(cursor.getInt(idx++));
//			business.setTitle(cursor.getString(idx++));
//			business.setLink(cursor.getString(idx++));
//			business.setSeq(cursor.getString(idx++));
//			business.setAuthor(cursor.getString(idx++));
//			business.setDescription(cursor.getString(idx++));
//			business.setCategory(cursor.getString(idx++));
//			business.setPubDate(cursor.getString(idx++));
//			business.setReqstDt(cursor.getString(idx++));
//			business.setArea(cursor.getString(idx));
//			businesses.add(business);
//		}
//		cursor.close();
//		dbObj.close();
//		return businesses;
//	}
//
////	public List<Business> getBusinessBySettingPersonalize(String strArea, String strAptitude) {
////		Map<String, Object> params = new HashMap<String, Object>();
////		params.put("keyword", strArea);
////		params.put("keyword_", strAptitude);
////		return executeForBeanList("getBusinessByPersonalize", params, Business.class);
////	}
//
//	/**
//	 * 20121122 요청에 의해 환경설정 설정정보에 따른 맞춤정보 검색 키워드 변경
//	 * ORM 에서 동적 쿼리를 제공하지 않아 어쩔 수 없이 환경설정 맞춤 정보는 코드에서..
//	 * 
//	 * @param strArea
//	 * @param strAptitudes
//	 * @return
//	 */
//	public List<Business> getBusinessBySettingPersonalize(String strArea, String strAptitudes) {
//		getDbObject();
//		String[] keywords = strAptitudes.split(",");
//		StringBuffer execSQL = new StringBuffer();
//		execSQL.append("SELECT * FROM tb_business WHERE (");
//		int cnt = 1;
//		for (String keyword : keywords) {
//			execSQL.append("title LIKE '%" + keyword.trim() + "%' OR description LIKE '%" + keyword.trim() + "%'");
//			if (cnt++ != keywords.length)
//				execSQL.append(" OR ");
//		}
//		execSQL.append(")");
//
//		// 지역 필터가 '전지역'이 아니라면 지역 검색 필터링 추가
//		if (!(strArea.equals("전지역")))
//			execSQL.append(" AND area LIKE '%" + strArea.trim() + "%'");
//
//		execSQL.append(" ORDER BY title ASC;");
//
//		Logger.d(TAG, "SettingPersonalize [" + execSQL.toString() + "]");
//
//		Cursor cursor = dbObj.rawQuery(execSQL.toString(), null);
//		List<Business> businesses = new ArrayList<Business>();
//		while (cursor.moveToNext()) {
//			Business business = new Business();
//			int idx = 0;
//			business.setId(cursor.getInt(idx++));
//			business.setTitle(cursor.getString(idx++));
//			business.setLink(cursor.getString(idx++));
//			business.setSeq(cursor.getString(idx++));
//			business.setAuthor(cursor.getString(idx++));
//			business.setDescription(cursor.getString(idx++));
//			business.setCategory(cursor.getString(idx++));
//			business.setPubDate(cursor.getString(idx++));
//			business.setReqstDt(cursor.getString(idx++));
//			business.setArea(cursor.getString(idx));
//			businesses.add(business);
//		}
//		cursor.close();
//		dbObj.close();
//		return businesses;
//	}
//
//	public List<Business> getBusinessByStartUp() {
//		return executeForBeanList("getBusinessByStartUp", null, Business.class);
//	}
//
//	/**
//	 * 20121126 요청에 의해 환경설정 설정정보에 따른 창업정보 지역 키워드 변경
//	 * ORM 에서 동적 쿼리를 제공하지 않아 어쩔 수 없이 환경설정 창업정보는 코드에서..
//	 * 
//	 * @param strArea
//	 * @param strAptitudes
//	 * @return
//	 */
//	public List<Business> getBusinessByStartUp(String strArea) {
//		getDbObject();
//		StringBuffer execSQL = new StringBuffer();
//		execSQL.append("SELECT * FROM tb_business WHERE (title LIKE '%창업%' OR description LIKE '%창업%')");
//
//		// 지역 필터가 '전지역'이 아니라면 지역 검색 필터링 추가
//		if (!(strArea.equals("전지역")))
//			execSQL.append(" AND area LIKE '%" + strArea.trim() + "%'");
//
//		execSQL.append(" ORDER BY title ASC;");
//
//		Logger.d(TAG, "SettingStartUp [" + execSQL.toString() + "]");
//
//		Cursor cursor = dbObj.rawQuery(execSQL.toString(), null);
//		List<Business> businesses = new ArrayList<Business>();
//		while (cursor.moveToNext()) {
//			Business business = new Business();
//			int idx = 0;
//			business.setId(cursor.getInt(idx++));
//			business.setTitle(cursor.getString(idx++));
//			business.setLink(cursor.getString(idx++));
//			business.setSeq(cursor.getString(idx++));
//			business.setAuthor(cursor.getString(idx++));
//			business.setDescription(cursor.getString(idx++));
//			business.setCategory(cursor.getString(idx++));
//			business.setPubDate(cursor.getString(idx++));
//			business.setReqstDt(cursor.getString(idx++));
//			business.setArea(cursor.getString(idx));
//			businesses.add(business);
//		}
//		cursor.close();
//		dbObj.close();
//		return businesses;
//	}

}
